package cn.bugstack.xfg.dev.tech.trigger.http;

import cn.bugstack.xfg.dev.tech.api.response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/rag/")
public class RAGController {
    @Resource
    private OllamaChatClient ollamaChatClient;
    @Resource
    private TokenTextSplitter tokenTextSplitter;
    @Resource
    private SimpleVectorStore simpleVectorStore;
    @Resource
    private PgVectorStore pgVectorStore;
    @Resource
    private RedissonClient redissonClient;

    //上传文件
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public response<Object> upload(@RequestParam String ragTag, @RequestParam("file") List<MultipartFile> files) {
        log.info("-----rag:{}", ragTag);
        for (MultipartFile file : files) {
            TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(file.getResource());
            List<Document> documents = tikaDocumentReader.get();
            List<Document> documentSplitterList = tokenTextSplitter.apply(documents);
            documentSplitterList.forEach(document -> {
                document.getMetadata().put("knowledge", ragTag);

            });
            pgVectorStore.accept(documentSplitterList);
            RList<String> ragTagList = redissonClient.getList("ragTagList");
            if (!ragTagList.contains(ragTag)) {
                ragTagList.add(ragTag);
            }


        }
        return response.builder().code("200").info("上传成功").data("").build();

    }
    //查询所有的知识列表
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public response<Object> list() {
        RList<String> ragTagList = redissonClient.getList("ragTagList");
        return response.builder().code("200").info("查询成功").data(ragTagList).build();
    }
    //使用知识库



}
